import QtQuick
import QtQuick.Controls
import Qt.labs.platform

Item {
    id: ledEditItem
    width: 100
    height: 100

    signal rightBtnMenuClicked(var menuName)

    property real squareWidth: 50
    property real pressedX: 0
    property real pressedY: 0
    property real translateX: 0
    property real translateY: 0
    property real ledNumX: 1
    property real ledNumY: 1

    property int videoFrameCount: 0 // 当前视频帧计数
    property int listViewIndex: 0 // 当前ListView元素索引
    property color backgroundColor: "#2e2f30"
    property color footerbgColor: "#24292e"
    property double sliderToolHeight: 24
    property int footerFontSize: 15

    property bool clickedLeftBtn: false // 鼠标左键按下标志

    // 设置一帧灯珠颜色
    function setOneFrameLedColor(framePosition) {
        var ledNum = Number(myHandle.getMyProperty("lNum"))
        videoFrameCount = framePosition
        for(var i = 0; i < ledNum; i++) {
            ledEditListModel.setProperty(i, "ledColor", myHandle.getLedColor(i + framePosition * ledNum).toString());
//                console.log(myHandle.getLedColor(i + videoFrameCount * ledNum))
        }
    }
    // 获取一个灯珠颜色
    function getOneLedColor(whichOne) {
        var ledNum = Number(myHandle.getMyProperty("lNum"))
//        console.log(whichOne + videoFrameCount * ledNum)
        return myHandle.getLedColor(whichOne + videoFrameCount * ledNum).toString()
    }
    // 修改一个灯珠颜色
    function replaceOneLedColor(whichOne, color) {
        var ledNum = Number(myHandle.getMyProperty("lNum"))
        ledEditListModel.setProperty(whichOne, "ledColor", color.toString())
        myHandle.setLedColor(whichOne + videoFrameCount * ledNum, color)
    }
    // 设置显示的灯珠X轴数量
    function setDisplayLedNumX(ledNum) {
        // 根据之前的数量决定此次是追加还是移除
        ledNumX = ledNum
        var lastCount = ledEditListModel.count
        if(lastCount < ledNumX) {
            for(var i = lastCount; i < ledNumX; i++) {
                ledEditListModel.append({"ledColor": "#000000"})
            }
        } else if(lastCount > ledNumX) {
            for(var j = lastCount; j >= ledNumX; j--) {
                ledEditListModel.remove(j)
            }
        }
    }
    // 设置显示的灯珠Y轴数量
    function setDisplayLedNumY(ledNum) {
        ledNumY = ledNum
    }

    // 设置有效帧数显示和滑动条终点
    function setValidFrameNum(validFrameNum) {
        validFrameNumText.inputText = validFrameNum.toString()
        videoFrameSlider.to = validFrameNum
    }
    // 设置当前帧数显示和滑动条滑动值
    function setCurrentFrameNum(currentFrameNum) {
        currentFrameNumText.inputText = currentFrameNum // 更新当前帧数的显示
        videoFrameSlider.value = currentFrameNum
    }
    // 灯效播放定时器播放或暂停 true:播放 false:暂停
    function videoTimerPlayPause(flag) {
        if(flag) {
            if((videoFrameCount + 1) >= Number(myHandle.getMyProperty("fValidNum"))) videoFrameCount = 0
        }
        videoTimer.running = flag
    }
    // 设置灯效播放定时器周期
    function setTimerInterval(interval) {
        videoTimer.interval = interval
    }

    Connections {
        target: myHandle

        function onDeviceStateChanged(state) {
            heartBeatLine.hblRun = state
//            console.log(state)
        }
    }

    Rectangle {
        id: ledEditRect
        width: parent.width
        anchors.top: parent.top
        anchors.bottom: ledEditFooterRect.top
        color: backgroundColor
        clip: true

        MouseArea {
            anchors.fill: parent
            acceptedButtons: Qt.LeftButton | Qt.RightButton

            CustomMenu1 {
                id: rightBtnMenu
                width: 120
                height: 60
                color: "#34393e"
                cmTextColor: "#e1e4e8"
                cmFontSize: 14
                cmItemHeight: height / menuText.length

                property var menuText: ["设置播放帧率", "裁剪和保留"]

                Component.onCompleted: {
                    for(var i = 0; i < menuText.length; i++) {
                        rightBtnMenu.cmListModel.set(i, {"mText": menuText[i]})
                    }
                }

                onCustomMenuClicked: function(index) {
                    switch(index) {
                        case 0: rightBtnMenuClicked("playRate"); break;
                        case 1: rightBtnMenuClicked("frameCut"); break;
                    }
                }
            }

            onClicked: function(mouse) {
                if(mouse.button === Qt.RightButton) {
                    rightBtnMenu.open(mouse.x, mouse.y)
                } else {
                    focus = true
                }
            }

            onWheel: function(wheel) {
                // 根据鼠标滑轮方向去改变方块边长属性 实现缩放
                if(wheel.angleDelta.y > 0) {
                    squareWidth = squareWidth >= 100 ? 100 : squareWidth + 5
                } else {
                    squareWidth = squareWidth <= 10 ? 10 : squareWidth - 5
                }
            }
            onPressed: function(mouse) {
                focus = true
                if(mouse.button === Qt.LeftButton) {
                    clickedLeftBtn = true
                    // 按下则重新记录  当前坐标减去之前的偏移值是为了保持增量
                    pressedX = mouseX - translateX
                    pressedY = mouseY - translateY
                } else {
                    clickedLeftBtn = false
                }
            }
            onPositionChanged: function(mouse) {
                if(clickedLeftBtn) {
                    // 鼠标位置变化则改变偏移值  此时会在之前偏移值上继续进行增量加减
                    var offsetX = mouseX - pressedX
                    var offsetY = mouseY - pressedY
                    if(offsetX >= (squareWidth / 2 - ledEditColumn.width) && offsetX <= (parent.width - squareWidth / 2)) {
                        translateX = offsetX
                    }
                    if(offsetY >= (squareWidth / 2 - ledEditColumn.height) && offsetY <= (parent.height - squareWidth / 2)) {
                        translateY = offsetY
                    }
                }
            }
        }
        // 居中快捷键
        Shortcut {
            sequence: "Ctrl+ "

            onActivated: {
                translateX = ledEditRect.width/2 - ledEditColumn.width/2
                translateY = ledEditRect.height/2 - ledEditColumn.height/2
            }
        }
        Shortcut {
            sequence: " "

            onActivated: {
                videoTimerPlayPause(!videoTimer.running)
            }
        }

        Column {
            id: ledEditColumn
            width: ledNumX * squareWidth
            height: ledNumY * squareWidth + spacing
            x: translateX
            y: translateY
            spacing: 5

            ListModel {
                id: ledEditListModel
                ListElement { ledColor: "#000000" }
            }

            ListView {
                id: ledEditListViewX
                width: parent.width
                height: squareWidth
                clip: true
                orientation: ListView.Horizontal
                interactive: false

                model: ledEditListModel
                delegate: Rectangle {
                    id: delegateRect1
                    width: squareWidth
                    height: squareWidth
                    border.width: 1
                    border.color: "#FFFFFF"
                    color: ledColor

                    MouseArea {
                        anchors.fill: parent
                        acceptedButtons: Qt.RightButton // 只接受右键
                        hoverEnabled: true
                        // 是否传递到被覆盖的MouseArea
                        propagateComposedEvents: true

                        onClicked: {
                            // 右键点击则赋值当前ListView的索引号 并打开颜色盘
                            listViewIndex = index
                            colorDialog.currentColor = getOneLedColor(index)
                            colorDialog.open()
                        }

                        onEntered: {
                            // 鼠标悬停则根据当前灯珠信息设置显示内容
                            ledInfoModel.setProperty(0,"inputText1",(index + 1).toString())
                            ledInfoModel.setProperty(1,"inputText1",(1).toString())
                            ledInfoModel.setProperty(2,"inputText1",getOneLedColor(index))
                        }
                    }
                }
            }
        }
    }

    Rectangle {
        id: ledEditFooterRect
        width: parent.width
        height: 30
        anchors.bottom: parent.bottom
        color: footerbgColor
        clip: true

        Row {
            id: ledEditFooterRow
            anchors.fill: parent

            Row {
                id: sliderTool
                width: parent.width / 3
                height: parent.height
                spacing: 5
                topPadding: (sliderTool.height - sliderToolHeight) / 2

                TitleTextInput {
                    id: validFrameNumText
                    width: 120
                    height: sliderToolHeight
                    titleText: qsTr("有效帧数:")
                    titleWidth: 80
                    textColor: "#d1d5da"
                    textSize: footerFontSize
                    inputBackColor: footerbgColor
                    inputBorderWidth: 1
                    inputBorderColor: "#888888"
                    inputText: ""
                    inputReadOnly: true
                    inputValidator: RegularExpressionValidator { regularExpression: /[0-9]+/ } // 文本验证器 仅可输入数字
                    inputRadius: 4
                }

                TitleTextInput {
                    id: currentFrameNumText
                    width: 120
                    height: sliderToolHeight
                    titleText: qsTr("当前帧数:")
                    titleWidth: 80
                    textColor: "#d1d5da"
                    textSize: footerFontSize
                    inputBackColor: footerbgColor
                    inputBorderWidth: 1
                    inputBorderColor: "#888888"
                    inputText: "1"
                    inputValidator: RegularExpressionValidator { regularExpression: /[0-9]+/ } // 文本验证器 仅可输入数字
                    inputRadius: 4

                    onInputTextChanged: {
                        setCurrentFrameNum(Number(currentFrameNumText.inputText))
                    }
                }


            }

            Row {
                id: ledEffectPlayRow
                width: parent.width / 3
                height: parent.height
                spacing: 5
                topPadding: (sliderTool.height - sliderToolHeight) / 2

                AsButton {
                    id: leftSliderBtn
                    width: sliderToolHeight
                    height: sliderToolHeight
                    text: qsTr("<")
                    backColor: footerbgColor
                    textColor: "#d1d5da"
                    borderWidth: 1
                    font.pixelSize: footerFontSize
                    itemRadius: 4

                    onClicked: {
                        // 按下将滑动条滑动值减少一个步长值
                        videoFrameSlider.value -= videoFrameSlider.stepSize
                        videoTimerPlayPause(false)
                    }
                }

                Slider {
                    id: videoFrameSlider
                    width: parent.width - leftSliderBtn.width - rightSliderBtn.width - sliderTool.spacing * 2
                    height: sliderToolHeight
                    snapMode: Slider.SnapAlways
                    stepSize: 1
                    from: 1
                    to: 30
                    value: 1

                    onPressedChanged: {
                        videoTimerPlayPause(false)
                    }

                    onValueChanged: {
                        setCurrentFrameNum(videoFrameSlider.value)
                        setOneFrameLedColor(videoFrameSlider.value - 1)
                    }
                }

                AsButton {
                    id: rightSliderBtn
                    width: sliderToolHeight
                    height: sliderToolHeight
                    text: qsTr(">")
                    backColor: footerbgColor
                    textColor: "#d1d5da"
                    borderWidth: 1
                    font.pixelSize: footerFontSize
                    itemRadius: 4

                    onClicked: {
                        // 按下将滑动条滑动值增加一个步长值
                        videoFrameSlider.value += videoFrameSlider.stepSize
                        videoTimerPlayPause(false)
                    }
                }
            }

            Row {
                id: ledInfoRow
                width: parent.width / 3
                height: parent.height

                Item {
                    width: parent.width - 290
                    height: 10
                }

                HeartBeatLine {
                    id: heartBeatLine
                    y: 6
                    width: 80
                    height: 30
                    hblRun: false
                }

                ListModel {
                    id: ledInfoModel
                    ListElement { titleText1: qsTr("行:"); inputText1: "1"; width1: 50; titleWidth1: 20 }
                    ListElement { titleText1: qsTr("列:"); inputText1: "1"; width1: 50; titleWidth1: 20 }
                    ListElement { titleText1: qsTr("色值:"); inputText1: "#000000"; width1: 110; titleWidth1: 30 }
                }

                Repeater {
                    id: ledInfoRepeater
                    model: ledInfoModel
                    delegate: TitleTextInput {
                        width: width1
                        height: parent.height
                        titleText: titleText1
                        titleWidth: titleWidth1
                        textColor: "#d1d5da"
                        textSize: footerFontSize
                        inputBackColor: footerbgColor
                        inputBorderWidth: 0
                        inputText: inputText1
                        inputReadOnly: true
                        inputValidator: RegularExpressionValidator { regularExpression: /[0-9]+/ } // 文本验证器 仅可输入数字
                    }
                }
            }
        }
    }

    Timer {
        id: videoTimer
        interval: 33
        running: false
        triggeredOnStart: true
        repeat: true

        onTriggered: {
            // 触发则将当前视频帧的颜色数据填充到矩形中
            setOneFrameLedColor(videoFrameCount)
            videoFrameCount += 1
            // 当前视频帧计数自增或循环
            if(videoFrameCount >= Number(myHandle.getMyProperty("fValidNum")))
                videoTimerPlayPause(false)
            ledEditView.setCurrentFrameNum(videoFrameCount)
        }
    }

    ColorDialog {
        id: colorDialog

        // 选择接受信号
        onAccepted: {
            // 修改此灯珠颜色
            replaceOneLedColor(listViewIndex, colorDialog.color)
//            console.log(colorDialog.color)
        }
    }
}
